print ('第一个_len_')
# 获取字符串的长度
s = "hello"
length_of_s = len(s) 
lst = [1, 2, 3, 4, 5]
length_of_lst = len(lst) 
d = {'a': 1, 'b': 2, 'c': 3}
length_of_d = len(d) 
print ('第二个__init__')
#初始化新构建对象的对象的状态
class Person:
    def __init__(self, name, age):
        self.name = name 
        self.age = age   
alice = Person('A', 25)
print(alice.name)  
print(alice.age)
print ('第三个_doc_')
#储存对象的文档字符串
def greet(name):
    return f"Hello, {name}!"
print(greet.__doc__)
print ('第四个_dir_')
#列出对象属性
import math
math_attributes = dir(math)
print("math模块的属性和方法:")
for attr in math_attributes:
  print(attr)
print ('第五个_mul_')
#定义对象的乘法行为
class Scalar:
    def __init__(self, value):
        self.value = value
    def __mul__(self, other):
        if isinstance(other, Scalar):
            return Scalar(self.value * other.value)
        else:
            return self.value * other
print ('第六个_ne_')
#定义对象“不等于”的比较
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __ne__(self, other):
        if not isinstance(other, Person):
            return True
        return self.name != other.name or self.age != other.age
print ('第七个_new_')       
#控制对象的实例化过程
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        print("Singleton instance initialized.")
print ('第八个_ge_')
#用于对象比较
class Number:
    def __init__(self, value):
        self.value = value
    def __ge__(self, other):
        if isinstance(other, Number):
            return self.value >= other.value
        elif isinstance(other, (int, float)):
            return self.value >= other
        else:
            raise TypeError("Unsupported operand type for >=: '{}' and '{}'".format(type(self).__name__, type(other).__name__))  
print ('第九个_or_')
#模拟逻辑或操作
def _or_(a, b):
    return a or b
print ('第十个_ior_')
#按位
def _ior_(a, b):
    return a | b
print ('第十一个_imul_')
#按位乘法
def _imul_(a, b):
    return a & b
print ('第十二个_ge_')
#比较对象
def _ge_(a, b):
    return a >= b
print ('第十三个_hash_')
#定义对象的哈希值
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __hash__(self):
        return hash((self.name, self.age))

    def __eq__(self, other):
        if isinstance(other, Person):
            return self.name == other.name and self.age == other.age
        return False
print ('第十四个_repr_')
#调试和记录
class SimpleClass:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return f'SimpleClass(value={self.value})'
obj = SimpleClass(42)
print(obj) 
repr_str = obj.__repr__()
print(repr_str) 
    
print ('第十五个_lt_')
#比较两个对象
class Number:
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        if isinstance(other, Number):
            return self.value < other.value
        return NotImplemented
print ('第十六个_le_')
#比较两个函数
class Number:
    def __init__(self, value):
        self.value = value
    def __le__(self, other):
        if isinstance(other, Number):
            return self.value <= other.value
        return NotImplemented
print ('第十七个_add_')
#对象相加
def _add_(x,y):
    return x + y
print ('第十八个_iadd_')
#原地加法赋值
class MyNumber:
    def __init__(self, value):
        self.value = value

    def __iadd__(self, other):
        if isinstance(other, MyNumber):
            self.value += other.value
        elif isinstance(other, (int, float)):
            self.value += other
        else:
            raise TypeError(f"Unsupported operand type for +=: '{type(other).__name__}' and 'MyNumber'")
        return self
    def __str__(self):
        return f"MyNumber({self.value})"
print ('第十九个eq_')
#定义对象之间的等于关系
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __eq__(self, other):
        if isinstance(other, Person):
            return self.name == other.name and self.age == other.age
        return False
print ('第二十个_len_')
def _len_(obj):
    return len(obj)

print ('第二十一个_le_')
# 定义小于等于比较逻辑。
class Number:
    def __init__(self, value):
        self.value = value
    def __le__(self, other):
        if isinstance(other, Number):
            return self.value <= other.value
        return NotImplemented
print ('第二十二个count')
#统计列表中某个元素出现的次数
my_list = [1, 2, 2, 3, 4, 4, 4]
count_of_two = my_list.count(2)  
print(count_of_two)  
count_of_three = my_list.count(3)  
print(count_of_three)  
print('第二十三个index')
#找到子字符串在字符串的索引
s = "Hello, world!"
substr = "world"
try:
    index_position = s.index(substr)
    print(f"子字符串 '{substr}' 在字符串中首次出现的索引位置是: {index_position}")
except ValueError:
    print(f"子字符串 '{substr}' 在字符串中未找到。")
print ('第二十四个get')
#获取数据
my_dict = {
    'name': 'Alice',
    'age': 60,
    'city': 'New York'
}
def get_value(dictionary, key):
    return dictionary.get(key)
print ('第二十五个append')
#添加元素
def append_to_list(original_list, item):
    original_list.append(item)
print ('第二十六个sort')
#元素排序
def sort_list(input_list):
    input_list.sort()
print ('第二十七个remove')
#移除元素
def remove_from_list(input_list, item):
    try:
        input_list.remove(item)
    except ValueError:
        print(f"元素 {item} 不在列表中，无法移除。")
print ('第二十八个_getitem_')
#支持引索操作
class MySequence:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        if not isinstance(index, int):
            raise TypeError("Index must be an integer")
        if index < 0 or index >= len(self.data):
            raise IndexError("Index out of range")
        return self.data[index]
my_sequence = MySequence([10, 20, 30, 40, 50])
first_element = my_sequence[0] 
print(first_element) 
third_element = my_sequence[2] 
print(third_element)
try:
    nonexistent_element = my_sequence[10]
except IndexError as e:
    print(e) 
print ('第二十九个formkeys')
#参数放入列表
def formkeys(*args):
    keys = list(args)
    return keys
print ('第三十个_reduce_ex_')
#添加注释
from functools import reduce

def reduce_ex(function, iterable, initializer=None):
    if initializer is not None:
        it = iter(iterable)
        return reduce(function, it, initializer)
    else:
        return reduce(function, iterable)
print ('第三十一个_init_subclass_')
#子代创建自动调用
class BaseClass:
    def __init_subclass__(cls, is_abstract=False, **kwargs):       super().__init_subclass__(**kwargs) 
    cls.is_abstract = is_abstract 
    if is_abstract:
            cls.__abstractmethods__ = set()
class AbstractChild(BaseClass, is_abstract=True):
    def some_abstract_method(self):
        raise NotImplementedError("子类必须实现这个方法")
class NonAbstractChild(AbstractChild):
    def some_abstract_method(self):
        print("NonAbstractChild 实现了这个方法")
print ('第三十二个reduce')
#元素积累
from functools import reduce
def concatenate(s1, s2):
    return s1 + s2
strings = ["Hello", " ", "World", "!"]
concatenated_string = reduce(concatenate, strings)
print(f"连接后的字符串是: {concatenated_string}")
print ('第三十三个_getattribute_')
#访问对象属性
class MyClass:
    def __init__(self, value):
        self._value = value 
    def __getattribute__(self, name):
        if name.startswith('_'):
            raise AttributeError(f"访问私有属性 {name} 是不允许的")
        return super().__getattribute__(name)
print ('第三十四个_gt_')
#比较大于关系
num1 = 10
num2 = 3
print ('第三十五个clear')
#清除数据结构
def clear_list(lst):
    lst.clear()
print ('第三十六个copy')
#复制数据结构
def copy_list(original_list):
    return original_list.copy()
print ('第三十七个pop')
#移除或返回指定元素
def pop_element(lst, index):
    return lst.pop(index)
is_greater = _gt_(num1, num2)
print ('第三十八个class')
#定义类
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height
    def perimeter(self):
        return 2 * (self.width + self.height)
print ('第三十九个_subclasshood_')
#子类继承关系
class Parent:
    pass
class Child(Parent):
    pass
class Grandchild(Child):
    pass
def check_subclasshood(subclass, superclass):
    return issubclass(subclass, superclass)
print ('第四十个_new_')
#控制初始化
class MyClass:
    _instances = 0
    def __new__(cls, *args, **kwargs):
        cls._instances += 1
        instance = super().__new__(cls)       
        instance.instance_number = cls._instances
        return instance
    def __init__(self, value):
        self.value = value